package com.bit.book.interceptor;

import com.bit.book.model.Result;
import com.bit.book.model.UserInfo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    public boolean checkUser(HttpSession session){
        if(session == null ||session.getAttribute("Constants.SESSION_USER_KEY")==null){
            log.warn("用户未登录");
            return false;
        }

        UserInfo userInfo = (UserInfo)session.getAttribute("Constants.SESSION_USER_KEY");
        if(userInfo == null || userInfo.getId() <= 0){
            log.warn("用户登录失败");
            // 用户未登录
            return false;
        }
        log.info("用户登录成功");
        return true;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("prehandle: 目标方法执行前执行的代码");
        HttpSession session = request.getSession(false);
        if (!checkUser(session)) {
            response.setContentType("application/json;charset=utf-8"); // 修改内容类型为 JSON
            response.setStatus(401);
            String msg = "{\"error\": \"用户未登录\"}"; // 修改为 JSON 格式的消息,要使用转义字符
            response.getOutputStream().write(msg.getBytes("UTF-8"));
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("postHandle: 目标方法执行后执行");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("afterCompletion: 视图渲染完成以后, 执行改方法");
    }
}
